import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
                             QPushButton, QLabel, QLineEdit, QFileDialog, QTabWidget, QTextEdit)
import os
from ansys.fluent.core import launch_fluent  # 确保导入正确


class MeshTab(QWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        vbox = QVBoxLayout()

        # 加载网格文件
        hbox1 = QHBoxLayout()
        gridFileLabel = QLabel('加载网格文件', self)
        self.gridFileLineEdit = QLineEdit(self)
        self.gridFileLineEdit.setPlaceholderText('请选择网格文件路径')
        gridFileButton = QPushButton('浏览...', self)
        gridFileButton.clicked.connect(self.browseGridFile)
        hbox1.addWidget(gridFileLabel)
        hbox1.addWidget(self.gridFileLineEdit)
        hbox1.addWidget(gridFileButton)
        hbox1.setSpacing(10)
        hbox1.addStretch()
        vbox.addLayout(hbox1)

        # 网格划分按钮
        self.meshButton = QPushButton("启动网格划分任务", self)
        self.meshButton.clicked.connect(self.run_meshing_task)
        vbox.addWidget(self.meshButton)

        self.setLayout(vbox)

    def browseGridFile(self):
        options = QFileDialog.Options()
        gridFilePath, _ = QFileDialog.getOpenFileName(
            self, "选择网格文件", "", "All Files (*);;Text Files (*.txt)", options=options)
        if gridFilePath:
            self.gridFileLineEdit.setText(gridFilePath)

    def run_meshing_task(self):
        geom = self.gridFileLineEdit.text()
        if not os.path.isfile(geom):
            self.parent.consoleOutput.append(f"几何体文件 {geom} 不存在")
            return

        # 启动 Fluent 并设置为父窗口的 session 属性
        self.parent.session = launch_fluent(
            precision="double", processor_count=4, mode="meshing")
        self.parent.consoleOutput.append(
            "<span style='color:green;'>Fluent 已启动（网格划分模式）</span>")

        self.parent.session.workflow.InitializeWorkflow(
            WorkflowType="Watertight Geometry")
        self.parent.session.workflow.TaskObject["Import Geometry"].Arguments = dict(
            FileName=geom, LengthUnit="mm")
        self.parent.session.workflow.TaskObject["Import Geometry"].Execute()

        self.parent.session.workflow.TaskObject["Add Local Sizing"].AddChildToTask(
        )
        self.parent.session.workflow.TaskObject["Add Local Sizing"].Execute()

        self.parent.session.workflow.TaskObject["Generate the Surface Mesh"].AddChildToTask(
        )
        self.parent.session.workflow.TaskObject["Generate the Surface Mesh"].Execute(
        )

        self.parent.session.workflow.TaskObject["Describe Geometry"].UpdateChildTasks(
            SetupTypeChanged=False)
        self.parent.session.workflow.TaskObject["Describe Geometry"].Arguments = dict(
            SetupType="The geometry consists of only fluid regions with no voids")
        self.parent.session.workflow.TaskObject["Describe Geometry"].UpdateChildTasks(
            SetupTypeChanged=True)
        self.parent.session.workflow.TaskObject["Describe Geometry"].Execute()

        self.parent.session.workflow.TaskObject["Update Boundaries"].Execute()
        self.parent.session.workflow.TaskObject["Update Regions"].Execute()
        self.parent.session.workflow.TaskObject["Add Boundary Layers"].Execute(
        )
        self.parent.session.workflow.TaskObject["Generate the Volume Mesh"].Execute(
        )

        self.parent.session.tui.mesh.check_mesh()
        self.parent.consoleOutput.append("网格质量检查完成")

        output_mesh = "wind.msh.h5"
        self.parent.session.tui.file.write_mesh(output_mesh)
        self.parent.consoleOutput.append(f"网格文件已保存为 {output_mesh}")

        self.parent.setMeshFile(output_mesh)  # 将网格文件传递给父窗口

        # self.parent.session.exit()
        # self.consoleOutput.append("Fluent 会话已关闭")
